<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div style="display: flex">
      <img src="./img/liao.jpg" alt="" />
      <button onclick="change()">转换</button>
      <canvas width="100" height="117"></canvas>
    </div>

    <script>
      function change() {
        const imgEl = document.querySelector("img");
        const cvs = document.querySelector("canvas");
        const ctx = cvs.getContext("2d");

        ctx.drawImage(imgEl, 0, 0);
        const imageData = ctx.getImageData(0, 0, imgEl.width, imgEl.height);
        for (let i = 0; i < imageData.data.length; i += 4) {
          const r = imageData.data[i];
          const g = imageData.data[i + 1];
          const b = imageData.data[i + 2];
          const avg = (r + g + b) / 3;
          imageData.data[i] =
            imageData.data[i + 1] =
            imageData.data[i + 2] =
              avg;
        }
        ctx.putImageData(imageData, 0, 0);
      }
    </script>
  </body>
</html>
